// app.js
Page({
  data:{
    db:null,
    userInfo:{},
    hasLoaded: false, // 标记是否已加载
    showModal:false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('this.data.hasLoaded',this.data.hasLoaded)
    if (this.data.hasLoaded) return; // 如果已加载，直接返回
    this.setData({
      hasLoaded:true
    })

    // 正常的初始化逻辑
    console.log('登录页 onLoad 执行');
    console.log('options',options)
    if (options.interver) {
      wx.setStorageSync('inviterCode',options.interver);
    }

    const app = getApp();
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db
    })

    this.checkLoginStatus() 
  },
  // getUserList(){
  //   const userInfo = wx.getStorageSync('userInfo');
  //   console.log('getUserList userInfo',userInfo)

  //   const result = await wx.cloud.callFunction({
  //     name: 'login'
  //   });
  //   console.log('getUserList result',result)
  //   // 步骤3：处理返回结果
  //   if (result.result.status === 'registered') {
  //     console.log('已注册用户:', result.result.userInfo);
  //     wx.navigateTo({ url: '/pages/home/home' });
  //   } else {
  //     // 新用户需补充信息
  //     this.getUserProfile(result.result.openid);
  //   }


  //  return this.data.db.collection('userList').where({
  //   }).get()
  //   .then(res => {
  //     return res
  //   })
  // },
  toBusiness(){
    const app = getApp();
    const token = wx.getStorageSync('token');
    const inviterCode = wx.getStorageSync('inviterCode');
    const userInfo = wx.getStorageSync('userInfo');
    wx.hideLoading()
    console.log('to Business')
    console.log('to Business checkLoginStatus token',token,inviterCode)

    wx.switchTab({
      url: '/pages/business/index'
    })
      
  },
  // 检查登录状态
  async checkLoginStatus() {
    const app = getApp();
    const token = wx.getStorageSync('token');
    const inviterCode = wx.getStorageSync('inviterCode');
    const userInfo = wx.getStorageSync('userInfo');
    console.log('checkLoginStatus token',token,inviterCode,userInfo)
    if(token){
      wx.showLoading({
        title: `用户信息读取中...`,
      })
      const getLogin = await wx.cloud.callFunction({
        name: 'login'
      });
      console.log('getLogin',getLogin)
      const result = getLogin.result
      if(result && result.data && result.data.length > 0){
        // if(result.data.length > 0){
          wx.setStorageSync('userInfo', result.data[0])
          console.log('userInfo  inviterCode',result.data[0],inviterCode,result.data[0].nameCode)
          if(inviterCode !== '' && result.data[0].nameCode !== inviterCode){
            this.data.db.collection('userList').where({
              nameCode:inviterCode
            }).get()
            .then(res => {
              if(res && res.data && res.data.length > 0 ){
                const interver__openid = res.data[0]._openid
                const interver_userId = res.data[0].userId
                const interver_nickName = res.data[0].nickName
                const interver_avatarUrl = res.data[0].avatarUrl
                console.log('has nameCode',interver__openid,interver_userId,interver_nickName)
                this.data.db.collection('inviterList').where({
                  interver:inviterCode,
                  beiInterver:app.getNameCode(userInfo.signature)
                }).get()
                .then(res => {
                  if(res && res.data && res.data.length > 0){
                    this.toBusiness()
                  }else{
                    this.data.db.collection('inviterList').add({
                      data:{
                        interver__openid:interver__openid,
                        interver_userId:interver_userId,
                        interver_nickName:interver_nickName,
                        interver:inviterCode,
                        interver_avatarUrl:interver_avatarUrl,
                        beiInterver:app.getNameCode(userInfo.signature),
                      },
                      success: res => {
                        console.log('inviterList add success',interver__openid)
                        // 向邀请人发送邀请成功的信息通知
                        this.data.db.collection('newsList').add({
                          data:{
                            nickName:interver_nickName,
                            nameCode:inviterCode,
                            receiverId:interver__openid,
                            taitou:interver_nickName + '的厨房',
                            message:userInfo.nickName+'已加入你的厨房啦',
                            tip:'厨房新成员加入提醒',
                            isRead:false,
                            createTime:new Date().getTime()
                          },
                          success: res => {
                            console.log('newsList add success',interver__openid)
                            // 向邀请人发送邀请成功的信息通知
                            // this.toBusiness()
                          }
                        })
                        this.toBusiness()
                      }
                    })
                  }
                }).catch(() => {
                  this.checkLoginStatus()
                })
              }else{
                this.toBusiness()
              }
            }).catch(() => {
              this.toBusiness()
            })
          }else{
            this.toBusiness()
          }

        // }else{
        //   this.getWechatUserInfo()
        // }

      }else{
        console.log('no userList',userInfo)
        if(userInfo && userInfo.signature){
          this.data.db.collection('userList').add({
            data: {
              signature:userInfo.signature,
              userId:userInfo.signature,
              userInfoAll:userInfo,
              nameCode:app.getNameCode(userInfo.signature),
              description:'',
              nickName:'用户'+app.getNickName(userInfo.signature),
              avatarUrl:userInfo.avatarUrl,
            },
            success: async(res) => {
              const getOpenid = await wx.cloud.callFunction({
                name: 'openid'
              });
              console.log('getOpenid',getOpenid.result.openid)
              this.data.db.collection('newsList').add({
                data:{
                  nickName:'系统',
                  nameCode:'',
                  taitou:'系统信息',
                  message:'欢迎您的到来，让我们这个小地方蓬荜生辉！',
                  tip:'厨房登录提醒',
                  isRead:false,
                  receiverId:getOpenid.result.openid,
                  createTime:new Date().getTime()
                },
                success: res => {
                  console.log('newsList add 系统 success')
                }
              })
              this.checkLoginStatus()
            }
          })
        }else{
          wx.clearStorageSync(); // 同步方法，立即生效
          this.checkLoginStatus()
        }
      }
    }else{
      this.showLoginModal()
    }
  },
  showLoginModal() {
    // 显示加载框（带文字）
    // wx.showLoading({
    //   title: '加载中...', // 最多显示7个汉字
    //   mask: true        // 是否显示透明蒙层（防止触摸穿透）
    // })
    //   this.getWechatUserInfo()
    //   return;
    console.log('showLoginModal  showLoginModal',this.data.showModal)
    if(this.data.showModal)return;
    this.setData({
      showModal:true
    })
    wx.showModal({
      title: '登录提示',
      content: '请先登录以使用完整功能',
      confirmText: '微信登录',
      cancelText: '暂不登录',
      success: (res) => {
        if (res.confirm) {
          wx.showModal({
            title: '登录提示',
            content: '获取个人身份信息',
            confirmText: '确定',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                // 显示加载框（带文字）
                  // 延迟 300ms 确保模态框完全关闭
                  wx.showLoading({
                    title: '加载中...', // 最多显示7个汉字
                    mask: true        // 是否显示透明蒙层（防止触摸穿透）
                  })
                  this.getWechatUserInfo()
              }else{
                this.handleRejectLogin()
              }
            }
          });
        }else{
          this.handleRejectLogin()
        }
      }
    });
  },
  getWechatUserInfo() {
    console.log('getWechatUserInfo')
    wx.getUserProfile({
      desc: '用于完善会员信息',
      success: (res) => {
        console.log('re getUserProfile',res)
        this.setData({
          userInfo:res
        })
        
        // 获取code
        wx.login({
          success: (loginRes) => {
            console.log('wx.login',loginRes)
            this.sendToServer(loginRes.code,this.data.userInfo)
          }
        })
      }
    })
  },

  sendToServer(code, userInfo) {
    wx.setStorageSync('token', code)
    wx.setStorageSync('userInfo', userInfo)
    this.checkLoginStatus()
    return;
    wx.request({
      url: 'https://your.api/login',
      method: 'POST',
      data: { code, nickName: userInfo.nickName },
      success: (res) => {
        wx.setStorageSync('token', res.data.token)
      }
    })
  },

  handleRejectLogin() {
    wx.showToast({
      title: '需要登录才能使用',
      icon: 'none',
      complete: () => {
        setTimeout(() => {
          wx.reLaunch({ url: '/pages/login/index' })
        }, 1500)
      }
    })
  },
})
